<template>
  <view class="container" :style="appThemeStyle">
    <NavBar/>
    <view class="apply" v-if="applyList.length">
      <view class="item" v-for="(item, index) in applyList" :key="index" @click="handleMenu(item)">
        <image :src="$image(`/storeminiapp/${item.icon}.png`)"></image>
        <view class="text">{{ item.name }}</view>
      </view>
      <view class="item" v-if="applyList.length > 3 && businessType !== 0" @click="$navTo('pages/apply/index')">
        <image :src="$image('/storeminiapp/icon_app_all.png')"></image>
        <view class="text">全部</view>
      </view>
    </view>
    <view v-if="$checkModule('ly_home_data_view')">
      <view class="dashboard">
        <view class="dis-flex flex-x-between">
          <view class="title">营业数据分析</view>
          <view class="more" @click="$navTo('pages/dashboard/index')">
            <text>更多数据</text>
            <text class="iconfont icon-arrow-right"></text>
          </view>
        </view>
        <view class="gmv-total">
          <view class="gmv-item">
            <view class="name">GMV <text class="iconfont circle" @click="handleTips(1)">&#xe6b1;</text></view>
            <view class="number price-icon"><text>{{ (gmv.goodsAmount || 0).toFixed(2) }}</text></view>
            <view class="desc">
              <text class="float">较上期</text>
              <text :class="['iconfont normal', { active: gmv.goodsAmountGrowthRatio > 0 }]">{{ gmv.goodsAmountGrowthRatio > 0 ? '&#xe69c;' : '&#xe69a;' }}</text>
              <text class="normal price-icon" :class="{ active: gmv.goodsAmountGrowthRatio > 0 }">{{ gmv.goodsAmountGrowthRatio }}%</text>
            </view>
          </view>
          <view class="gmv-item">
            <view class="name">有效订单数 <text class="iconfont circle" @click="handleTips(2)">&#xe6b1;</text></view>
            <view class="number price-icon"><text>{{ gmv.validOrderCount }}</text></view>
            <view class="desc">
              <text class="float">较上期</text>
              <text :class="['iconfont normal', { active: gmv.validOrderCountGrowthRatio > 0 }]">{{ gmv.validOrderCountGrowthRatio > 0 ? '&#xe69c;' : '&#xe69a;' }}</text>
              <text class="normal price-icon" :class="{ active: gmv.validOrderCountGrowthRatio > 0 }">{{ gmv.validOrderCountGrowthRatio }}%</text>
            </view>
          </view>
          <view class="gmv-item">
            <view class="name">总补贴 <text class="iconfont circle" @click="handleTips(3)">&#xe6b1;</text></view>
            <view class="number price-icon"><text>{{ (gmv.discountPrice || 0).toFixed(2) }}</text></view>
            <view class="desc">
              <text class="float">较上期</text>
              <text :class="['iconfont normal', { active: gmv.discountPriceGrowthRatio > 0 }]">{{ gmv.discountPriceGrowthRatio > 0 ? '&#xe69c;' : '&#xe69a;' }}</text>
              <text class="normal price-icon" :class="{ active: gmv.discountPriceGrowthRatio > 0 }">{{ gmv.discountPriceGrowthRatio }}%</text>
            </view>
          </view>
        </view>
        <view class="compare">
          <view class="compare-cell">
            <view class="compare-cell__ele">
              <view class="name">有效GMV <text class="iconfont circle" @click="handleTips(4)">&#xe6b1;</text></view>
              <view class="number price-icon">{{ gmv.validAmount }}</view>
            </view>
            <view class="compare-cell__ele">
              <view class="name">上期</view>
              <view class="number price-icon">{{ gmv.priorValidAmount}}</view>
            </view>
            <view class="compare-cell__ele">
              <view class="name">{{ gmv.validAmountGrowthRatio > 0 ? '增长' : '降低' }}</view>
              <view class="number">
                <text :class="['iconfont normal', { active: gmv.validAmountGrowthRatio > 0 }]">{{ gmv.validAmountGrowthRatio > 0 ? '&#xe69c;' : '&#xe69a;' }}</text>
                <text class="normal price-icon" :class="{ active: gmv.validAmountGrowthRatio > 0 }">{{ gmv.validAmountGrowthRatio }}%</text>
              </view>
            </view>
          </view>
          <view class="compare-cell">
            <view class="compare-cell__ele">
              <view class="name">单均价 <text class="iconfont circle" @click="handleTips(5)">&#xe6b1;</text></view>
              <view class="number price-icon">{{ gmv.avgPrice }}</view>
            </view>
            <view class="compare-cell__ele">
              <view class="name">上期</view>
              <view class="number price-icon">{{ gmv.priorAvgPrice }}</view>
            </view>
            <view class="compare-cell__ele">
              <view class="name">{{ gmv.avgPriceGrowthRatio > 0 ? '增长' : '降低' }}</view>
              <view class="number">
                <text :class="['iconfont normal', { active: gmv.avgPriceGrowthRatio > 0 }]">{{ gmv.avgPriceGrowthRatio > 0 ? '&#xe69c;' : '&#xe69a;' }}</text>
                <text class="normal price-icon" :class="{ active: gmv.avgPriceGrowthRatio > 0 }">{{ gmv.avgPriceGrowthRatio }}%</text>
              </view>
            </view>
          </view>
          <view class="compare-cell" v-if="businessType === 0">
            <view class="compare-cell__ele">
              <view class="name">会员总数</view>
              <view class="number price-icon">{{ gmv.memberCount }}</view>
            </view>
            <view class="compare-cell__ele">
              <view class="name">上期</view>
              <view class="number price-icon">{{ gmv.priorMemberCount }}</view>
            </view>
            <view class="compare-cell__ele">
              <view class="name">{{ gmv.memberCountGrowthRatio > 0 ? '增长' : '降低' }}</view>
              <view class="number">
                <text :class="['iconfont normal', { active: gmv.memberCountGrowthRatio > 0 }]">{{ gmv.memberCountGrowthRatio > 0 ? '&#xe69c;' : '&#xe69a;' }}</text>
                <text class="normal price-icon" :class="{ active: gmv.memberCountGrowthRatio > 0 }">{{ gmv.memberCountGrowthRatio }}%</text>
              </view>
            </view>
          </view>
        </view>
      </view>
      <view class="sales-compare">
        <view class="title">销售渠道占比</view>
        <view class="select-list">
          <view
            :class="['select-item', { active: index === currentIndex }]"
            v-for="(item, index) in selectList"
            :key="index"
            @click="selectItem(index)"
          >
            {{ item.title }}
          </view>
        </view>
        <view class="charts">
          <qiun-data-charts
            :opts="opts"
            type="pie"
            :localdata="localData"
            :canvas2d="!isDev"
          />
        </view>
      </view>
    </view>
    <Empty v-else tips="暂无权限"/>
    <!-- 动态TabBar -->
    <TabBar/>
  </view>
</template>

<script>
import NavBar from "@/components/navbar"
import store from '@/store'
import * as DashboardApi from '@/api/dashboard'
import Empty from '@/components/empty'
import { cloneObj } from '@/utils/util'
import * as StoreApi from "@/api/store"
import ScanCodeTypeEnum from "@/common/enum/scanCodeType"
import TabBar from '@/components/tabbar'
import PickerStatusEnum from "@/common/enum/setting/pickerStatus"
import SettingModal from '@/common/model/Setting'

const isDev = process.env.NODE_ENV === 'development'

const couponPage = 'orderpages/coupon/index'

export default {
  name: "index",
  components: { NavBar, Empty, TabBar },
  data() {
    return {
      isDev,
      opts: {
        extra: {
          pie: {
            activeOpacity: 0.5,
            activeRadius: 10,
            offsetAngle: 0,
            labelWidth: 15,
            border: true,
            borderWidth: 1,
            borderColor: "#FFFFFF"
          }
        },
        legend: {
          lineHeight: 24
        }
      },
      selectList: [{ title: '营业额' }, { title: '有效订单数' }],
      currentIndex: 0,
      queryParams: {
        start: this.$moment().format("YYYY-MM-DD 00:00:00"),
        end: this.$moment().format("YYYY-MM-DD 23:59:59"),
        timeType: 1,
        thirdChannelId: '',
        deliveryType: ''
      },
      localData: [],
      gmv: {},
      // 控制onShow事件是否刷新列表
      canReset: false,
      currentPage: 'pages/home/index'
    }
  },
  computed: {
    store() {
      return store.getters.store
    },
    shopId() {
      return this.store.id
    },
    businessType() {
      return store.getters.businessType
    },
    menus() {
      return store.getters.menus
    },
    applyList() {
      const menus = cloneObj(this.menus)
      const apply = menus.find(val => val.name === '应用')?.children
      if (!apply) return []
      this.addLevelToTree(apply)
      let result = this.getLevelItems(apply)
      const removeKeys = ['门店商品', '新品申请']
      const fIndex = result.findIndex(item => item.name === '新品申请')
      const list = result.splice(fIndex, 1)
      result = result.concat(list)
      return (this.businessType !== 1 ? result.filter(item => !removeKeys.includes(item.name))
        : result).slice(0, 4)
    },
    pickerStatus() {
      return store.getters.pickerStatus
    },
  },
  onLoad() {
    // 注册全局事件订阅: 是否刷新列表
    uni.$on('syncRefresh', canReset => {
      this.canReset = canReset
    })
    this.onRefreshPage()
  },
  /**
   * 生命周期函数--监听页面的卸载
   */
  onUnload() {
    // 卸载全局事件订阅
    uni.$off('syncRefresh')
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if (this.canReset) {
      this.onRefreshPage()
      this.canReset = false
    }
    uni.hideTabBar()
  },
  onReady() {
    if (this.pickerStatus === PickerStatusEnum.REST.value) {
      this.$confirm(
        () => SettingModal.setPickUser(PickerStatusEnum.LEISURE.value),
        {title: '拣货员', content: '当前是休息状态，您是否确定切换为“在线”？'}
      )
    }
  },
  methods: {
    handleMenu(item) {
      if (item.path !== couponPage) return this.$navTo(item.path)
      uni.scanCode({
        success: res => {
          const { result: verifyCode } = res
          StoreApi.scanCode({
            type: ScanCodeTypeEnum.COUPON_VERIFICATION.value,
            scanResult: verifyCode,
            shopId: this.store.id
          }).then(({ data }) => {
            this.$navTo(item.path, { ...data, verifyCode })
          }).catch(({ msg }) => {
            this.$toast(msg ||'未识别到该条码')
          })
        },
        fail: () => {
          this.$toast('未识别到该条码')
        }
      })
    },
    onRefreshPage() {
      if (this.businessType !== 0) {
        this.queryParams.organizationIds = this.shopId
      } else {
        delete this.queryParams.organizationIds
      }
      this.getDashboard()
      this.getShopChannelData()
    },
    selectItem(index) {
      this.currentIndex = index
      this.getShopChannelData(index)
    },
    getDashboard() {
      DashboardApi.dashboard(this.queryParams).then(res => {
        this.gmv = res.data
      })
    },
    getShopChannelData(index) {
      DashboardApi.getShopChannelData(this.queryParams).then(res => {
        const { data } = res
        this.localData = data.map(item => {
          return {
            value: index === 0 ? parseInt(item.gmv) : parseInt(item.y),
            text: item.channelName,
          }
        })
      })
    },
    collectNamesByKeys(tree, keys, result = []) {
      tree.forEach((node) => {
        if (keys.includes(node.name)) {
          result.push(node.name)
        }
        if (node.children) {
          this.collectNamesByKeys(node.children, keys, result)
        }
      })
      return result
    },
    addLevelToTree(tree, level = 0) {
      tree.forEach(node => {
        node.level = level
        if (node.children?.length) {
          this.addLevelToTree(node.children, level + 1)
        }
      })
    },
    getLevelItems(tree) {
      let levelItems = []
      const traverse = (nodes, level) => {
        nodes.forEach(node => {
          if (level === 1) {
            levelItems.push(node)
          }
          if (node.children?.length) {
            traverse(node.children, level + 1)
          }
        })
      }
      traverse(tree, 0)
      return levelItems
    },
    handleTips(value) {
      switch (value) {
        case 1:
          this.$toast('商品原价流水总额', 3000)
          break;
        case 2:
          this.$toast('已接单且未整单取消的订单数量', 3000)
          break;
        case 3:
          this.$toast('商家承担补贴+渠道承担补贴+品牌承担补贴', 3000)
          break;
        case 4:
          this.$toast('商品原价-商品单品补贴-商家整单补贴-商家运费补贴', 3000)
          break;
        case 5:
          this.$toast('商品原价-商品单品补贴-商家整单补贴-商家支付补贴', 3000)
          break;
        default:
          break;
      }
    },
  }
}
</script>

<style scoped lang="scss">
.container {
  padding: 24rpx;

  .apply {
    display: flex;
    padding: 32rpx 0;
    border-radius: 16rpx;
    background: #fff;

    .item {
      text-align: center;
      font-size: 26rpx;
      width: calc(100% / 4);

      image {
        width: 64rpx;
        height: 64rpx;
      }

      .text {
        color: #3D4146;
        margin-top: 16rpx;
      }
    }
  }

  .dashboard {
    background: #fff;
    padding: 24rpx;
    margin-top: 16rpx;
    border-radius: 16rpx;

    .title {
      font-size: 32rpx;
      font-weight: bold;
    }

    .more {
      font-size: 26rpx;
      color: #999999;
      display: flex;
      align-items: center;

      .iconfont {
        font-size: 30rpx;
      }
    }

    .gmv-total {
      display: flex;
      margin-top: 32rpx;

      .gmv-item {
        flex: 1;
        text-align: left;

        .name {
          font-size: 26rpx;

          .circle {
            color: #999;
          }
        }

        .number {
          font-weight: bold;
          margin: 12rpx 0;

          text {
            font-size: 38rpx;
          }
        }

        .desc {
          font-size: 24rpx;
          color: #999999;

          .float {
            margin-right: 8rpx;
          }

          .normal {
            color: #47D034;

            &.active {
              color: red;
            }
          }
        }
      }
    }

    .compare {
      margin-top: 32rpx;

      .compare-cell {
        background: #F5F6F9;
        border-radius: 16rpx;
        padding: 20rpx;
        margin-bottom: 16rpx;
        display: flex;

        &__ele {
          flex: 1;
          text-align: center;

          .name {
            font-size: 26rpx;
            color: #66696E;
          }

          .number {
            font-size: 30rpx;
            font-weight: bold;
            margin-top: 12rpx;
            display: flex;
            justify-content: center;
            align-items: center;

            .normal {
              color: #47D034;

              &.active {
                color: red;
              }
            }

            .iconfont {
              font-weight: normal;
            }
          }
        }
      }
    }
  }

  .sales-compare {
    background: #fff;
    padding: 24rpx;
    margin-top: 16rpx;
    border-radius: 16rpx;

    .title {
      font-size: 32rpx;
      font-weight: bold;
    }

    .select-list {
      margin-top: 32rpx;
      display: flex;

      .select-item {
        margin-right: 16rpx;
        border-radius: 8rpx;
        border: 1rpx solid var(--eeeeee, #EEE);
        background: #FFF;
        font-size: 24rpx;
        color: #666666;
        padding: 10rpx 24rpx;

        &.active {
          background: #f8f8f8;
          color: #333333;
          font-weight: bold;
        }
      }
    }

    .charts {
      background: #ffffff;
      width: 100%;
      height: 500rpx;
    }
  }
}
</style>
